const mysql = require('mysql')

function connect() {
    return mysql.createConnection({
        host: "101.33.198.189",
        user: "ceshi",
        password: "ceshi",
        database: "panorama",
        multipleStatements: true
    })
}

//获取查询结果
function querySql(sql) {
    const conn = connect();
    return new Promise((resolve, reject) => {
        try {
            conn.query(sql, (err, results) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(results)
                }
            })
        } catch (e) {
            reject(e)
        } finally {
            conn.end()
        }
    })
}

//从查询结果中筛选需要的那一个结果
function queryOne(sql) {
    return new Promise((resolve, reject) => {
        querySql(sql).then(results => {
            if (results && results.length > 0) {
                resolve(results[0])
            } else {
                resolve(null)
            }
        }).catch(err => {
            reject(err)
        })
    })
}


module.exports = {
    querySql,
    queryOne
}